import 'package:flutter/material.dart';
import 'package:kasax_demos2/entry/data_posts_test.dart';
import 'package:kasax_demos2/entry/entrys.dart';

/// 分页展示的数据表
class PaginatedDatatableDemo extends StatefulWidget {
  const PaginatedDatatableDemo({Key? key}) : super(key: key);

  @override
  _PaginatedDatatableDemoState createState() => _PaginatedDatatableDemoState();
}

class MyDataSource extends DataTableSource {
  List<Posts> _list = PostsDatas.TEST_POSTS;
  int _selectedRowCount = 0;

  @override
  DataRow? getRow(int index) {
    var e = _list[index];
    return DataRow.byIndex(cells: [
      DataCell(
        Text("${e.title}"),
      ),
      DataCell(Text("${e.author}")),
      DataCell(Padding(
        padding: EdgeInsets.all(10),
        child: Image.network(
          e.imageUrl,
          fit: BoxFit.cover,
        ),
      )),
    ], index: index);
  }

  @override
  bool get isRowCountApproximate => false;

  @override
  int get rowCount => _list.length;

  @override
  int get selectedRowCount => _selectedRowCount;

  /// 根据标题的内容长度进行排序
  //ascending是否使用升序排列
  void sort(getField(post), bool ascending) {
    _list.sort((a, b) {
      if (!ascending) {
        final c = a;
        a = b;
        b = c;
      }
      final aValue = getField(a);
      final bValue = getField(b);
      return Comparable.compare(aValue, bValue);
    });
    notifyListeners();
  }
}

class _PaginatedDatatableDemoState extends State<PaginatedDatatableDemo> {
  int _sortColumnIndex = 0;

  // 是否升序
  bool _sortAscending = true;

  MyDataSource _dataSource = MyDataSource();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Datatable-分页显示"),
      ),
      body: Container(
        padding: const EdgeInsets.all(8.0),
        child: PaginatedDataTable(
          header: Text("Posts"),
          headingRowHeight: 45,
          rowsPerPage: 5,
          source: _dataSource,
          columnSpacing: 8,
          sortColumnIndex: _sortColumnIndex,
          sortAscending: _sortAscending,
          horizontalMargin: 8,
          columns: [
            DataColumn(
                label: Text("title"),
                onSort: (int columnIndex, bool ascending) {
                  // 排序
                  _dataSource.sort((post) => post.title.length, ascending);

                  setState(() {
                    _sortColumnIndex = columnIndex;
                    _sortAscending = ascending;
                  });
                }),
            DataColumn(label: Text("author")),
            DataColumn(label: Text("image")),
          ],
        ),
      ),
    );
  }
}
